package com.jus.player.dao;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;

import com.jus.player.entity.WatchHistory;

@Database(entities = {WatchHistory.class}, version = 3,  exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    public abstract WatchHistoryDao watchHistoryDao();

    private static volatile AppDatabase INSTANCE;

    public static AppDatabase getInstance(final Context context) {
        if (INSTANCE == null) {
            synchronized (AppDatabase.class) {
                if (INSTANCE == null) {
                    INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                                    AppDatabase.class, "app_database")
                            //.addMigrations(MIGRATION_1_2)// 添加迁移策略
                            //.fallbackToDestructiveMigration() // 删除旧数据库
                            .build();
                }
            }
        }
        return INSTANCE;
    }

    static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            // 执行数据库变更操作
            database.execSQL("ALTER TABLE User ADD COLUMN phone TEXT DEFAULT NULL");
        }
    };
    //场景2：删除列（需要创建新表）
    static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            // 1. 创建新表
            database.execSQL("CREATE TABLE User_new (id INTEGER PRIMARY KEY, name TEXT)");

            // 2. 复制数据
            database.execSQL("INSERT INTO User_new (id, name) SELECT id, name FROM User");

            // 3. 删除旧表
            database.execSQL("DROP TABLE User");

            // 4. 重命名新表
            database.execSQL("ALTER TABLE User_new RENAME TO User");
        }
    };

    //场景3：修改列类型
    static final Migration MIGRATION_3_4 = new Migration(3, 4) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            // 1. 创建新结构表
            database.execSQL("CREATE TABLE User_new (id INTEGER PRIMARY KEY, name TEXT, join_date INTEGER)");

            // 2. 转换并复制数据
            database.execSQL("INSERT INTO User_new (id, name, join_date) " +
                    "SELECT id, name, strftime('%s', join_date) FROM User");

            // 3. 删除旧表
            database.execSQL("DROP TABLE User");

            // 4. 重命名新表
            database.execSQL("ALTER TABLE User_new RENAME TO User");
        }
    };
}